package es.cazadoresmadridejos.beans.controller.partner;

import javax.servlet.http.HttpServletRequest;

import org.displaytag.pagination.PaginatedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import es.cazadoresmadridejos.beans.manager.partner.PartnerManager;
import es.cazadoresmadridejos.model.Partner.HunterType;
import es.cazadoresmadridejos.objs.criteria.PartnerCriteria;
import es.cazadoresmadridejos.objs.web.Page;
import es.cazadoresmadridejos.web.util.ListUtil;


@SessionAttributes({"partnerCriteria"})
@Controller
public class PartnerListController {

	@Autowired private PartnerManager partnerManager;

	@RequestMapping(value="/partnerList*.html")
	public ModelAndView list(
			HttpServletRequest request,
			@RequestParam(value="id",required=false) Long id,
			@RequestParam(value="type",required=false) HunterType type,
			@RequestParam(value="name",required=false) String name,
			Boolean isList
			) throws Throwable {
		PartnerCriteria criteria = new PartnerCriteria();
		criteria.setType(type);
		criteria.setName(name);
		criteria.setId(id);
		
		ModelAndView mv;
		if(Boolean.TRUE.equals(isList)){
			mv = new ModelAndView("partnerList");
		}else{
			mv = new ModelAndView();
		}

		Page page = new Page(request,criteria);
		
		PaginatedList list = partnerManager.findAllPaginated(page);

		mv.addObject("list", list);
		mv.addObject("hunterTypes", HunterType.values());
		
		mv.addObject("hunterTypes", HunterType.values());
		mv.addObject("partnerCriteria", criteria);
		mv.addObject("type", "create");
		
		String string = partnerManager.findAllForAutocomplete();
		mv.addObject("partners",string);		
		
		return mv;
	}
	
	
	@RequestMapping(value="/partnerDelete.html")
	public ModelAndView delete(
			@RequestParam(value="id")Long id,
			HttpServletRequest request
			) throws Throwable {

		partnerManager.delete(id);
		
		return list(request, null,null, null,true);
	}
	
	@RequestMapping(value="/partnerImport.html")
	public ModelAndView importPartners(
			@RequestParam(value="id")Long id,
			HttpServletRequest request
			) throws Throwable {
		
		partnerManager.importPartners();
		
		return list(request, null,null, null,true);
	}
	
	
}
